﻿using LanguagePolish.Base;
using LanguagePolish.EntityModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Win32;

namespace LanguagePolish.ViewModels
{
    public class AddTeacherViewModel : BaseViewModel
    {
        public Teacher Teacher { get; private set; }

        public BitmapImage Photo
        {
            get { return Teacher.PhotoImage ?? GlobalSettings.NoPhotoImage; }
        }

        public TeacherAvailability[] Availability { get; private set; }

        public string Title { get; private set; }

        public bool HasErrors { get { return Teacher.HasErrors; } }
        //public bool TAHasErrors { get { return TeacherAvailability.HasErrors; } }

        public bool IsEdit { get; private set; }

        public AddTeacherViewModel(Teacher teacher, bool isEdit = false)
        {
            IsEdit = isEdit;
            Teacher = teacher;
            InitAvailabilities();
            InitTitle(isEdit);
        }

        private void InitTitle(bool isEdit)
        {
            Title = isEdit ? "Edit Teacher" : "Add New Teacher";
            OnPropertyChanged("Title");
        }

        /// <summary>
        /// Перепаковываем InitAvailabilities в массив для удобства.
        /// </summary>
        private void InitAvailabilities()
        {
            Availability = new TeacherAvailability[7];
            for (int i = 1; i <= 6; i++)
            {
                TeacherAvailability av = Teacher.TeacherAvailabilities.FirstOrDefault(t => t.WeekDay == i);
                if (av == null)
                {
                    av = new TeacherAvailability();
                    av.WeekDay = i;
                    Teacher.TeacherAvailabilities.Add(av);
                }
                Availability[i] = av;
            }
        }

        internal void LoadImage()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            bool? res = dlg.ShowDialog();
            if (res == true)
            {
                string path = dlg.FileName;
                BitmapImage img = Helper.ImageFromUri(path);
                Teacher.PhotoImage = img;
                OnPropertyChanged("Photo");
            }
        }
    }
}
